biAdhocNs.TableTreePanel = Ext.extend(Ext.tree.TreePanel, {
	title : tree.title,
	animate : true,
	autoScroll : true,
	rootVisible : false,
	enableDrop : false,
	enableDrag : true,
	root : {
		id : "9999",
		text : "9999",
		expanded : true
	},
	tableShowMap : new Ext.util.MixedCollection(),
	
	/**
	 * 初始化组件
	 */
	changeId : '',
	defaultMonth : '',
	changetype : '1',
	checkAttributes : new Ext.util.MixedCollection(),
	// border:false,
	ddGroup : 'treeColumnDDGroup',
	searchParameter : 'keywords',
	leafclickfn : function(node, e) {
	},
	searchValue : '',
	// 业务树数据结构描述，可选
	dataDesc : {
		rootIdValue : '6638bd3f-bf9f-494a-bc7b-fabf968a335c', // 根结点值，默认值：'0'，暂不支持为null的根结点
		idPropName : 'ID', // ID属性名，默认值：id
		parentPropName : 'PARENT_ID', // 父结点属性名，默认值：parentId
		textPropName : 'CNAME', // 名称属性名，默认值：name
		leafPropName : 'leaf' // 数据元素叶子属性名，默认值：leaf
		// leafTrueValue:'1' // 表示叶子结点的值，如果leafPropName是boolean类型则无需设置
	},
	// 当使用本地树过滤时重写该方法，返回值为false表示过滤掉该结点
	filterFn : function(node) {
		// 过虑掉conut为0的结点
		// alert(node.getRawNodeData().PARENT_ID);
		var parentId = node.getRawNodeData().PARENT_ID;
		var id = node.getRawNodeData().ID;
		var ret = id == '6638bd3f-bf9f-494a-bc7b-fabf968a335c'
				|| id == biAdhocNs.TableTreePanel.changeId
				|| parentId == biAdhocNs.TableTreePanel.changeId;
		return ret;
	},
	setToggleCheck : function(id, check) {

		if (id != null) {
			this.getNodeById(id).getUI().toggleCheck(check);
		}

		if (this.getNodeById(biAdhocNs.TableTreePanel.changeId)
				.findChild('id', id) !== null) {
			this.getNodeById(biAdhocNs.TableTreePanel.changeId)
					.findChild('id', id).getUI().toggleCheck(
							check);
		}
		if (Ext.getCmp('picturetree').checkAttributes.get(id) == null) {
//				Ext.getCmp('pic-edit-panel').setColumnStatus(
//						this.getNodeById(
//								biAdhocNs.TableTreePanel.changeId)
//								.findChild('id', id), check);
//				Ext.getCmp('picturetree').checkAttributes
//						.remove(this.getNodeById(
//								biAdhocNs.TableTreePanel.changeId)
//								.findChild('id', id));
		} else {
			Ext.getCmp('pic-edit-panel').setColumnStatus(
					Ext.getCmp('picturetree').checkAttributes
							.get(id), check);
			Ext.getCmp('picturetree').checkAttributes
					.remove(Ext.getCmp('picturetree').checkAttributes
							.get(id));
		}
	},
	listeners : {
		'beforecreatenode' : function(nodeAttr, nodeData) {

		},
		'expand' : function() {
			Ext.getCmp('group-condition-filter-panel').body
					.setStyle('background', '#FFFFFF');
			Ext.getCmp('accept-drop-target-panel').body
					.setStyle('background', '#FFFFFF');
			Ext.getCmp('client-label-panel').body.setStyle(
					'background', '#d9e8fb');
		},
		'click' : function(node, e) {
			if (node.attributes.leaf) {
				this.leafclickfn(node, e);
			}
		},
		'checkchange' : function(node, checked) {
			Ext.getCmp('pic-edit-panel').setColumnStatus(node,
					checked);
			var uxtreePanelCheckData = Ext
					.getCmp('picturetree').checkAttributes;
			if (checked) {
				uxtreePanelCheckData.add(node.id, node);
			} else {
				uxtreePanelCheckData.remove(node);
			}
		},
		'beforeload' : function(node) {
			if (node.id == '-1') {
				var url = [ biAdhocNs.sysUrl,
						'chart/findTableShowInfos' ].join('');
				var param = '';
				var rs = this.synchronizationAjax(url, param);
				for (var i = 0; i < rs.length; i++) {
					var row = rs[i];
					this.tableShowMap.add(row.tableId,
							row.tableId);
				}
			}
		},
		'expandnode' : function(node) {
			if (biAdhocNs.TableTreePanel.changeId == undefined) {
				biAdhocNs.TableTreePanel.changeId = '67622ac9-b601-4f89-830c-1669cd5ca410';
				/*
				 * var uxtreePanel = Ext.getCmp('picturetree');
				 * uxtreePanel.searchField.reset();
				 * uxtreePanel.cancelButton.hide();
				 * uxtreePanel.restoreTree();
				 * uxtreePanel.setFiltered(false);
				 * uxtreePanel.setFiltered(true);
				 */
			}
			// Ext.getCmp('picturetree').expandAll();

			if (node.id == biAdhocNs.TableTreePanel.changeId
					&& Ext.getCmp('picturetree').searchValue == 'search') {
				Ext.getCmp('picturetree').searchValue = '';
				var uxtreePanelCheckData = Ext
						.getCmp('picturetree').checkAttributes;
				if (true) {
					uxtreePanelCheckData.each(function(tempObj) {
						if (node.findChild('id',
								tempObj.id) !== null) {
							node.findChild('id',
									tempObj.id).getUI()
									.toggleCheck(true);
						}
					});
				}
			}
		}
	},
	getColumnIconCls : function(type, iskey) { // 根据不同的类型获取不同的节点图标
		if (type == biAdhocNs.COLTYPE_DEMENSION
				&& iskey == biAdhocNs.NOT_IS_PRIMARY_KEY) {
			return 'demension-column-icon';
		} else if (type == biAdhocNs.COLTYPE_DEMENSION
				&& iskey == biAdhocNs.IS_PRIMARY_KEY) {
			return 'demension-column_key-icon';
		} else if (type == biAdhocNs.COLTYPE_CODE
				&& iskey == biAdhocNs.NOT_IS_PRIMARY_KEY) {
			return 'code-column-icon';
		} else if (type == biAdhocNs.COLTYPE_CODE
				&& iskey == biAdhocNs.IS_PRIMARY_KEY) {
			return 'code-column-key-icon';
		} else if (type == biAdhocNs.COLTYPE_INTRVAL
				&& iskey == biAdhocNs.NOT_IS_PRIMARY_KEY) {
			return 'intrval-column-icon';
		} else if (type == biAdhocNs.COLTYPE_INTRVAL
				&& iskey == biAdhocNs.IS_PRIMARY_KEY) {
			return 'intrval-column-key-icon';
		} else if (type == biAdhocNs.COLTYPE_STAT_MON) {
			return 'key-column-icon';
		} else if (type == biAdhocNs.COLTYPE_STAT_CIT) {
			return 'key-column-icon';
		} else if (iskey == biAdhocNs.IS_PRIMARY_KEY) {
			return 'common-column-key-icon';
		} else {
			return 'common-column-icon';
		}
	},
	// 创建表属性节点, data is TnColumnInfos list
	createLeaves : function(node, data, tableName, tableCName, asName, xField, cyField, chartJson) {
		var dataLength = data.length;
		var s = '';
		var stip;
		var item;
		var tempObj;
		var treePanel = Ext.getCmp('picturetree');
		var checkedArray=treePanel.getCheckedArray(xField, cyField);
		for (var i=0; i < dataLength; i++) {
			item = data[i];
			var checkFlag=false;
			for(var c=0; c<checkedArray.length;c++){
				if(checkedArray[c] == item["name"]){
					checkFlag = true;
				}
			}

			item["text"] = item["cName"];
			item["name"] = item["name"];
			item["id"] = item["columnId"]; //取表字段id,如果使用字段名会导致：点一张表却选了另一张表同名字段的bug
			item["tableName"] = tableName;
			item["tableCName"] = tableCName;
			item["dataUnit"] = item["dataUnit"];
			item["decimalPrecision"] = item["decimalPrecision"];
			item["customStyle"] = item["customStyle"];
			item["asName"] = asName;
			item["order"] = item["priority"];
			item["leaf"] = true;
			item["checked"] = checkFlag;
			if (typeof item["colDesc"] == 'undefined'
					|| item["colDesc"] == '') {
				stip = s;
			} else {
				stip = [ item["colDesc"], '<br>', s ].join('');
			}
			item["qtip"] = stip;

			item["iconCls"] = Ext.getCmp('picturetree')
					.getColumnIconCls(item["colType"],
							item["isPrimaryKey"]);

			tempObj = new Ext.tree.TreeNode(item);

			node.appendChild(tempObj);
		}
		treePanel.loadModelInfo(xField, cyField, chartJson);
	},
	setDrillPath:function (columnId,dirllPath,xFieldCd){
		Ext.Ajax.request({
			url : [ biAdhocNs.sysUrl, 'chart/drillValue' ].join(''),
			params : {
				"columnId" : columnId,
				"drillPath" : dirllPath
			},
			method : 'post',
			callback : function(options, success, response) {
				if (!response.responseText == '') {
					if (success) {
						var responseMsg = Ext.util.JSON
								.decode(response.responseText);
						var btn = Ext.getCmp(biAnaly.COLUMN_BTN_ID_PREFIX + xFieldCd); 
						
					}
				} else {
					// Ext.Msg.alert('提示', '定义自定义标签失败');
				}
			}
		});
	},
	// 创建表节点 data is TnTableInfos list
	createTree : function(data, mask, x_Field, cy_Field, chartJson) {
		var dataLength = data.length;
		var item;
		var tempObj;
		for (var i=0; i < dataLength; i++) {
			item = data[i];

			item["text"] = item["cName"];
			item["id"] = item["name"];
			item["leaf"] = false;
			item["expanded"] = true;
			item["iconCls"] = "table-icon-1";

			tempObj = new Ext.tree.TreeNode(item);
			tempObj.draggable = false;

			this.root.appendChild(tempObj);
			// 创建子节点
			Ext.Ajax.request({
				url : [ biAdhocNs.sysUrl, 'chart/getTreeLeaves' ].join(''),
				params : {
					"tableId" : item["tableId"]
				},
				success : function(result, request) {
					if (mask) {
						mask.hide();
					}
					var data = Ext.util.JSON.decode(result.responseText);
					var treePanel = Ext.getCmp('picturetree');
					if (data != null && data != 'undefined') {
						treePanel.createLeaves(
							tempObj,
							data, 
							item["name"],
							item["cName"],
							item["asName"],
							x_Field, cy_Field, chartJson);
					}
					
				},
				failure : function(result, request) {
					if (mask) {
						mask.hide();
					}
					Ext.Msg.alert(tree.alert_prompt, tree.alert_loadfailure);
				}
			});
		}
	},
	loadModelInfo : function(x_Field, cy_Field, chartJson) {
		if(cy_Field != '') {
			var nodes = Ext.getCmp('picturetree').root.childNodes;
			var comp = Ext.getCmp('picturetree');
			if(nodes.length > 1 && nodes[1].childNodes.length > 0) {
				biAnaly.getMultiTableSettings(comp, null, cy_Field.mtRelationsBean.COLUMN, 0);
			}
		}
		if (x_Field != '') {
			var nodes = Ext.getCmp('picturetree').root.childNodes;
			var nodec = Ext.getCmp('picturetree').getNodeById(x_Field.columnId);
			//for (var i = 0; i < nodes.length; i++) {
				//if (nodes[i].findChild('name', x_Field.xFieldCd) != null) {
				//	nodec = nodes[0].findChild('name', x_Field.xFieldCd);
				//}
			//}
			if(nodec==null){
				return;
			}
			if(nodes.length == 1){   //区别单表，与多表，避免重复调用setColumnStatus方法
				Ext.getCmp('pic-edit-panel').setColumnStatus(nodec,
						true, 'axis-column');
			} else if (nodes.length > 1 && nodes[1].childNodes.length > 0) {
				Ext.getCmp('pic-edit-panel').setColumnStatus(nodec,
					true, 'axis-column');
			}
			var nodeIdArray = x_Field.drillPath.split(">");
			// 钻取路径
			if (nodeIdArray.length >1) {
				Ext.Ajax.request({
					url : [ biAdhocNs.sysUrl, 'chart/drillValue' ].join(''),
					params : {
						"columnId" : x_Field.columnId,
						"drillPath" : x_Field.drillPath
					},
					method : 'post',
					callback : function(options, success, response) {
						if (!response.responseText == '') {
							if (success) {
								var responseMsg = Ext.util.JSON
										.decode(response.responseText);
								var btn = Ext.getCmp(biAnaly.COLUMN_BTN_ID_PREFIX + x_Field.columnId); 
								var drillData=responseMsg.drillList[0];
								btn.setText(drillData.cnamePath);
								btn.attributes.text = drillData.drillPath;
								btn.namePath = drillData.namePath;
							}
						} else {
							// Ext.Msg.alert('提示', '定义自定义标签失败');
						}
					}
				});
			}
		}
		if (cy_Field.success && cy_Field != null) {
			if (cy_Field.cQueryBean != null
					&& cy_Field.cQueryBean != '') {
				var cField = cy_Field.cQueryBean.CONDITION;
				for (var i = 0; i < cField.length; i++) {
					var cInfo = cField[i];
					var nodec = Ext.getCmp('picturetree')
							.getNodeById(cInfo.name);
					if(nodes.length == 1){   //区别单表，与多表，避免重复调用setColumnStatus方法
						Ext.getCmp('pic-edit-panel').setColumnStatus(nodec, true,
								'report-filter');
						// 修改筛选条件
						btn = Ext.getCmp(biAnaly.COLUMN_BTN_ID_PREFIX
										+ cInfo.name);
						var op = cInfo.operator;
						var reOp;
						if (op.indexOf('AREA') != -1) {
							reOp = '';
						} else {
							reOp = op;
						}
						var text = [ btn.attributes.cName, reOp,
								cInfo.defaultValue ].join('');
						// btn.saveLeftHTML = cbleft.innerHTML;
						btn.saveRightHTML = cInfo.defaultValue; // 保存设计的html
						if (op.indexOf('AREA') != -1) {
							btn.opChar = ''; // 保存设计的操作符
						} else {
							btn.opChar = op; // 保存设计的操作符
						}
						if (op.indexOf('IN') != -1) { // 有in的操作，就每4个值换行
							var ts = text.split(',');
							var len = ts.length;
							if (len > 4) { // 有选择4个值以上的
								text = [ ts[0], '......',
										ts[len - 1] ].join('');
							}
						}
						btn.parameterType = cInfo.paramType;
						btn.atext = [ btn.attributes.name, reOp,
								cInfo.defaultValue ].join('');
						btn.avalue = cInfo.defaultValue;
						btn.setText(text); // 改变展现的文字
					} else if (nodes.length > 1 && nodes[1].childNodes.length > 0) {
						Ext.getCmp('pic-edit-panel').setColumnStatus(nodec, true,
								'report-filter');
						// 修改筛选条件
						btn = Ext.getCmp(biAnaly.COLUMN_BTN_ID_PREFIX
										+ cInfo.name);
						var op = cInfo.operator;
						var reOp;
						if (op.indexOf('AREA') != -1) {
							reOp = '';
						} else {
							reOp = op;
						}
						var text = [ btn.attributes.cName, reOp,
								cInfo.defaultValue ].join('');
						// btn.saveLeftHTML = cbleft.innerHTML;
						btn.saveRightHTML = cInfo.defaultValue; // 保存设计的html
						if (op.indexOf('AREA') != -1) {
							btn.opChar = ''; // 保存设计的操作符
						} else {
							btn.opChar = op; // 保存设计的操作符
						}
						if (op.indexOf('IN') != -1) { // 有in的操作，就每4个值换行
							var ts = text.split(',');
							var len = ts.length;
							if (len > 4) { // 有选择4个值以上的
								text = [ ts[0], '......',
										ts[len - 1] ].join('');
							}
						}
						btn.parameterType = cInfo.paramType;
						btn.atext = [ btn.attributes.name, reOp,
								cInfo.defaultValue ].join('');
						btn.avalue = cInfo.defaultValue;
						btn.setText(text); // 改变展现的文字				+ cInfo.name);
					}
					

				}
			}
			if (cy_Field.yQueryBean != null
					&& cy_Field.yQueryBean != '') {
				var yField = cy_Field.yQueryBean.MAIN_TABLE;
				for (var j = 0; j < yField.length; j++) {
					var yInfo = yField[j];
					
					var nodes = Ext.getCmp('picturetree').root.childNodes;
					/*for (var i = 0; i < nodes.length; i++) {
						if (nodes[i].findChild('name', x_Field.xFieldCd) != null) {
							var nodec = nodes[i].findChild('name', yInfo.NAME);
						}
					}*/
					var nodec = Ext.getCmp('picturetree').getNodeById(yInfo.COLUMN_ID);
					if(nodec==null){
						return;
					}
					if(nodes.length == 1){   //区别单表，与多表，避免重复调用setColumnStatus方法
						Ext.getCmp('pic-edit-panel').setColumnStatus(nodec, true,
								'numerical');
						btn = Ext.getCmp("sigma-number-btn"
								+ biAnaly.COLUMN_BTN_ID_PREFIX
								+ yInfo.COLUMN_ID);
						btny = Ext.getCmp(biAnaly.COLUMN_BTN_ID_PREFIX
										+ yInfo.COLUMN_ID);
						btn.setText(yInfo.SERIAS_NAME);
						btny.aggregate.name = yInfo.FUN;
						
						if (yInfo.FUN == "sum") {
							btny.aggregate.description = tree.yaxis.sum;
						} else if (yInfo.FUN == "count") {
							btny.aggregate.description = tree.yaxis.count;
						} else if (yInfo.FUN == "avg") {
							btny.aggregate.description = tree.yaxis.avg;
						} else if (yInfo.FUN == "max") {
							btny.aggregate.description = tree.yaxis.max;
						} else if (yInfo.FUN == "min") {
							btny.aggregate.description = tree.yaxis.min;
						} else {
							btny.aggregate.description = tree.yaxis.sum;
						}
						btny.setText(btny.aggregate.description
								+ '：' + btny.attributes.text);
						
						btny.attributes.dataUnit = yInfo.DATAUNIT;
						btny.attributes.decimalPrecision = yInfo.DECIMAL_PRECISION;
						btny.attributes.customStyle = yInfo.CUSTOM_STYLE;
					} else if (nodes.length > 1 && nodes[1].childNodes.length > 0) {
						Ext.getCmp('pic-edit-panel').setColumnStatus(nodec, true,
								'numerical');
						btn = Ext.getCmp("sigma-number-btn"
								+ biAnaly.COLUMN_BTN_ID_PREFIX
								+ yInfo.NAME);
						btny = Ext.getCmp(biAnaly.COLUMN_BTN_ID_PREFIX
										+ yInfo.NAME);
						btn.setText(yInfo.SERIAS_NAME);
						btny.aggregate.name = yInfo.FUN;
						
						if (yInfo.FUN == "sum") {
							btny.aggregate.description = tree.yaxis.sum;
						} else if (yInfo.FUN == "count") {
							btny.aggregate.description = tree.yaxis.count;
						} else if (yInfo.FUN == "avg") {
							btny.aggregate.description = tree.yaxis.avg;
						} else if (yInfo.FUN == "max") {
							btny.aggregate.description = tree.yaxis.max;
						} else if (yInfo.FUN == "min") {
							btny.aggregate.description = tree.yaxis.min;
						} else {
							btny.aggregate.description = tree.yaxis.sum;
						}
						btny.setText(btny.aggregate.description
								+ '：' + btny.attributes.text);
						
						btny.attributes.dataUnit = yInfo.DATAUNIT;
						btny.attributes.decimalPrecision = yInfo.DECIMAL_PRECISION;
						btny.attributes.customStyle = yInfo.CUSTOM_STYLE;
					}
					var chartProp = Ext
							.getCmp('anychart-prop-grid');
					chartProp.updateChartProp(chartJson);
					
				}
			}
		}
	},
	getCheckedArray: function(x_Field,cy_Field){
		var checkedArray = [];
		var csize = 0;
		var ysize = 0;
		if (x_Field != '') {
			checkedArray[0] = x_Field.xFieldCd;
		}
		if (cy_Field.success && cy_Field != null) {
			if (cy_Field.cQueryBean != null
					&& cy_Field.cQueryBean != '') {
				var cField = cy_Field.cQueryBean.CONDITION;
				csize = cField.length;
				for (var i = 0; i < csize; i++) {
					var cInfo = cField[i];
					checkedArray[i+1] = cInfo.name;
				}
			}
			if (cy_Field.yQueryBean != null
					&& cy_Field.yQueryBean != '') {
				var yField = cy_Field.yQueryBean.MAIN_TABLE;
				ysize = yField.length;
				for (var j = 0; j < ysize; j++) {
					var yInfo = yField[j];
					checkedArray[csize+1+j] = yInfo.NAME;
				}
			}
		}
		return checkedArray;
	},
	// 参数：prop = 属性，val = 值
	createJson : function(prop, val) {
		// 如果 val 被忽略
		if (typeof val === "undefined") {
			// 删除属性
			delete str1[prop];
		} else {
			// 添加 或 修改
			str1[prop] = val;
		}
	},
	getMultiRelationData : function(){  //多表关联配置数据获取
		var multiRelationData = {};
		if(Ext.getCmp("editGridPanelOfColumns") != undefined) {
			var array = new Array();
			if(Ext.getCmp("editGridPanelOfColumns").store != null) {
				 var myStore = Ext.getCmp("editGridPanelOfColumns").store;
				    var autoData = myStore.data.items;
				    for(var i = 0; i < autoData.length; i++ ) {
				    	if(autoData[i].data.dname != '') {
				    		array.push({
								"first_Column" : autoData[i].data.firstColumn,
								"last_Column" : autoData[i].data.lastColumn
							});
				    	}
				    }
				    multiRelationData.COLUMN = array;
			}
		}
		
	    return multiRelationData;
	},
	synchronizationAjax : function(url, para) {
		function createXhrObject() {
			var http;
			var activeX = [ 'MSXML2.XMLHTTP.3.0',
					'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP' ];
			try {
				http = new XMLHttpRequest();
			} catch (e) {
				for (var i = 0; i < activeX.length; ++i) {
					try {
						http = new ActiveXObject(activeX[i]);
						break;
					} catch (e) {
						;
					}
				}
			} finally {
				return http;
			}
		};
		var conn = createXhrObject();
		if (para != null && para != ''
				&& typeof (para) != 'undefined') {
			url = [ url, '?', para ].join('');
		}
		conn.open("GET", url, false);
		conn.send(null);
		if (conn.responseText != '') {
			var rs;
			try {
				rs = Ext.util.JSON.decode(conn.responseText);
			} catch (e) {
				return null;
			}
			return rs;
		} else {
			return null;
		}
	}
});

Ext.reg('uc_tabletreepanel', biAdhocNs.TableTreePanel);
